package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password){
        JsonResult jsonResult = new JsonResult();
        try {
            Employee employee = employeeService.login(username,password);
            // session.setAttribute("EMPLOYEE_IN_SESSION",employee);
            UserContextUtil.setEmployee(employee);
            // 登录成功查员工的权限
            List<String> expressions = permissionService.queryPermissionByEmployeeId(employee.getId());
            // session.setAttribute("EXPRESSIONS_IN_SESSION",expressions);
            UserContextUtil.setExpressions(expressions);
            jsonResult.setSuccess(true);
            jsonResult.setMsg("登录成功");
            return jsonResult;
        }catch (Exception e){
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMsg(e.getMessage());
            return jsonResult;
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        // session.removeAttribute("EMPLOYEE_IN_SESSION");
        UserContextUtil.removeEmployee();
        return "redirect:/static/login.html";
    }
}
